﻿using System;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using HtmlAgilityPack;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace 软构作业Winform
{
    public partial class Form4 : Form
    {
        private static readonly HttpClient httpClient = new HttpClient();

        private readonly object lockObject = new object();

        public Form4()
        {
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            InitializeComponent();
            httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36");
        }

        private void Form4_Load(object sender, EventArgs e)
        {

        }

        private async void BtnSearch_Click(object sender, EventArgs e)
        {
            var keyword = textBox1.Text;

            // 启动双线程并行搜索
            var taskBaidu = Task.Run(() => BaiduSearch(keyword));
            var taskBing = Task.Run(() => BingSearch(keyword));

            // 异步等待结果更新UI
            UpdateTextBox(textBox4, await taskBaidu);
            UpdateTextBox(textBox3, await taskBing);
        }

        // 线程安全的UI更新 
        private void UpdateTextBox(TextBox box, string content)
        {
            if (box.InvokeRequired)
                box.BeginInvoke(new Action(() => box.Text = content));
            else
                box.Text = content;
        }

        private string BingSearch(string keyword)
        {
            using (var client = new HttpClient())
            {
                // 模拟浏览器请求头 
                client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36");

                var response = client.GetAsync($"https://www.bing.com/search?q={Uri.EscapeDataString(keyword)}").Result;
                var html = response.Content.ReadAsStringAsync().Result;

                // 使用HtmlAgilityPack解析 
                var doc = new HtmlAgilityPack.HtmlDocument();
                doc.LoadHtml(html);

                // 提取搜索结果文本
                var nodes = doc.DocumentNode.SelectNodes("//div[@class='b_caption']/p");
                var allText = string.Join(" ", nodes.Select(n =>
    WebUtility.HtmlDecode(n.InnerText.Trim())));

                // 前200字符 
                return allText.Substring(0, Math.Min(200, allText.Length));
            }
        }

        private string BaiduSearch(string keyword)
        {
            const string apiUrl = "https://www.baidu.com/s?tn=json";
            using var client = new HttpClient();

            // 反爬头信息
            client.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (iPhone; CPU iPhone OS 17_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148");
            client.DefaultRequestHeaders.Add("Viewport-Width", "390");
            client.DefaultRequestHeaders.Add("Accept", "application/json");
            client.Timeout = TimeSpan.FromSeconds(15);

            try
            {
                // 构建UTF-8编码参数
                var queryParams = new Dictionary<string, string> {
            { "wd", Uri.EscapeDataString(keyword) },
            { "rn", "30" }, { "pn", "0" }, { "q5", "1" }, { "ie", "utf-8" }
        };
                var encodedParams = string.Join("&", queryParams.Select(kv =>
                    $"{Uri.EscapeDataString(kv.Key)}={Uri.EscapeDataString(kv.Value)}"));

                var response = client.GetAsync($"{apiUrl}?{encodedParams}").Result;
                response.EnsureSuccessStatusCode();

                // 多编码兼容读取
                using var stream = response.Content.ReadAsStreamAsync().Result;
                using var reader = new StreamReader(stream, Encoding.GetEncoding("GBK"));
                var rawResponse = reader.ReadToEnd();

                if (!IsValidJson(rawResponse))
                    throw new JsonException("Invalid JSON: " + rawResponse.Substring(0, 50));

                var json = JObject.Parse(rawResponse);
                var results = json["feed"]?["entry"]?.Select(e => new
                {
                    Title = e["title"]?.ToString(),
                    Content = e["subTitle"]?.ToString() ?? e["abs"]?.ToString()
                }).Where(r => !string.IsNullOrEmpty(r.Content));

                if (results == null || !results.Any())
                    return "未找到有效内容（请尝试更换关键词或检查网络）";

                // 结果清洗与拼接
                var cleanText = string.Join(" ", results
                    .Select(r => $"{WebUtility.HtmlDecode(r.Title)}:{WebUtility.HtmlDecode(r.Content)}")
                    .Where(t => !t.Contains("广告") && !t.Contains("百度热榜")));

                return cleanText.Length > 200 ? cleanText[..197] + "..." : cleanText;
            }
            catch (HttpRequestException ex)  // 处理API错误
            {
                return ex.StatusCode switch
                {
                    HttpStatusCode.TooManyRequests => "请求频繁被限制，请降低调用频率",
                    HttpStatusCode.Forbidden => "访问被拒绝（可能需申请API权限）",
                    _ => $"网络错误: {ex.Message}"
                };
            }
            catch (Exception ex)
            {
                return $"系统异常: {ex.Message}";
            }
        }

        private bool IsValidJson(string str)
        {
            try
            {
                JToken.Parse(str);
                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}